<template>
  <div class="test-data-view">
    <!-- 数据导航 -->
    <div class="data-navigation">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="基本信息" name="basic"></el-tab-pane>
        <el-tab-pane 
          v-for="group in dataGroups" 
          :key="group.groupId" 
          :label="group.groupName" 
          :name="group.groupId"
        ></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 基本信息 -->
    <div v-if="activeTab === 'basic'" class="data-section">
      <el-descriptions :column="2" border title="检测基本信息" size="medium">
        <el-descriptions-item label="样品编号">
          {{ testData.basicInfo?.sampleNo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="项目名称">
          {{ testData.basicInfo?.projectName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="检测日期">
          {{ formatDate(testData.basicInfo?.testDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="执行标准">
          {{ testData.basicInfo?.standardCode || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="检测人员">
          {{ testData.basicInfo?.tester || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="环境条件">
          {{ testData.basicInfo?.environment || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 参数组数据 -->
    <div v-else class="data-section">
      <div 
        v-for="group in currentGroups" 
        :key="group.groupId" 
        class="param-group"
      >
        <h3 class="group-title">
          {{ group.groupName }}
          <el-tag v-if="group.isNested" size="mini" type="info">嵌套组</el-tag>
          <el-tag v-if="group.allowDynamicRows" size="mini" type="warning">
            动态表格 ({{ getGroupRowCount(group) }}行)
          </el-tag>
        </h3>

        <!-- 嵌套组 -->
        <div v-if="group.isNested" class="nested-groups">
          <div 
            v-for="childGroup in group.childGroups" 
            :key="childGroup.groupId" 
            class="child-group"
          >
            <h4 class="child-group-title">{{ childGroup.groupName }}</h4>
            <param-data-table 
              :params="childGroup.paramItems"
              :data="getChildGroupData(group.groupId, childGroup.groupId)"
            />
          </div>
        </div>

        <!-- 动态表格 -->
        <div v-else-if="group.allowDynamicRows" class="dynamic-table-group">
          <el-table
            :data="getGroupRows(group.groupId)"
            border
            size="mini"
            style="width: 100%"
            empty-text="暂无数据"
          >
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column
              v-for="param in group.paramItems"
              :key="param.paramCode"
              :label="getParamLabel(param)"
              :min-width="param.columnWidth || 120"
            >
              <template #default="scope">
                <param-value-display
                  :param="param"
                  :value="scope.row[param.paramCode]"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 普通参数组 -->
        <div v-else class="normal-group">
          <param-data-table 
            :params="group.paramItems"
            :data="getGroupData(group.groupId)"
          />
        </div>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="data-stats">
      <el-card shadow="never">
        <div slot="header" class="stats-header">
          <span>数据统计</span>
        </div>
        <div class="stats-content">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ totalParams }}</div>
                <div class="stat-label">总参数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ baseParamsCount }}</div>
                <div class="stat-label">基础参数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ calcParamsCount }}</div>
                <div class="stat-label">计算参数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ filledParamsCount }}</div>
                <div class="stat-label">已填写</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import ParamDataTable from './ParamDataTable.vue'
import ParamValueDisplay from './ParamValueDisplay.vue'
import { formatDate } from '@/utils/tools'

export default {
  name: 'TestDataView',
  components: {
    ParamDataTable,
    ParamValueDisplay
  },
  props: {
    testData: {
      type: Object,
      required: true,
      default: () => ({
        basicInfo: {},
        groups: []
      })
    }
  },
  data() {
    return {
      activeTab: 'basic'
    }
  },
  computed: {
    dataGroups() {
      return this.testData.groups || []
    },
    
    currentGroups() {
      if (this.activeTab === 'basic') return []
      return this.dataGroups.filter(group => group.groupId === this.activeTab)
    },
    
    totalParams() {
      let count = 0
      this.traverseParams(() => count++)
      return count
    },
    
    baseParamsCount() {
      return this.countParamsByType('base')
    },
    
    calcParamsCount() {
      return this.countParamsByType('calculation')
    },
    
    filledParamsCount() {
      let count = 0
      this.traverseParams((param, value) => {
        if (value && value.value !== '' && value.value !== null && value.value !== undefined) {
          count++
        }
      })
      return count
    }
  },
  methods: {
    /**
     * 格式化日期
     */
    formatDate(dateString) {
      if (!dateString) return '-'
      return formatDate(dateString, 'YYYY-MM-DD')
    },
    
    /**
     * 获取参数标签
     */
    getParamLabel(param) {
      let label = param.paramName || param.paramCode
      if (param.unit) {
        label += ` (${param.unit})`
      }
      if (param.isMultiMeasure && param.multiMeasureCount > 1) {
        label += ` [${param.multiMeasureCount}次]`
      }
      return label
    },
    
    /**
     * 获取组数据
     */
    getGroupData(groupId) {
      const group = this.testData.groups.find(g => g.groupId === groupId)
      return group?.params || {}
    },
    
    /**
     * 获取子组数据
     */
    getChildGroupData(groupId, childGroupId) {
      const group = this.testData.groups.find(g => g.groupId === groupId)
      if (!group || !group.childGroups) return {}
      
      const childGroup = group.childGroups.find(cg => cg.groupId === childGroupId)
      return childGroup?.params || {}
    },
    
    /**
     * 获取组行数据
     */
    getGroupRows(groupId) {
      const group = this.testData.groups.find(g => g.groupId === groupId)
      return group?.rows || []
    },
    
    /**
     * 获取组行数
     */
    getGroupRowCount(group) {
      if (!group.allowDynamicRows) return 1
      const groupData = this.testData.groups.find(g => g.groupId === group.groupId)
      return groupData?.rows?.length || 0
    },
    
    /**
     * 遍历所有参数
     */
    traverseParams(callback) {
      this.dataGroups.forEach(group => {
        if (group.isNested) {
          group.childGroups.forEach(childGroup => {
            this.traverseGroupParams(childGroup.paramItems, group.groupId, childGroup.groupId, callback)
          })
        } else if (group.allowDynamicRows) {
          const groupData = this.testData.groups.find(g => g.groupId === group.groupId)
          if (groupData?.rows) {
            groupData.rows.forEach((row, rowIndex) => {
              this.traverseGroupParams(group.paramItems, group.groupId, null, callback, rowIndex, row)
            })
          }
        } else {
          this.traverseGroupParams(group.paramItems, group.groupId, null, callback)
        }
      })
    },
    
    /**
     * 遍历组参数
     */
    traverseGroupParams(params, groupId, childGroupId, callback, rowIndex = null, rowData = null) {
      params.forEach(param => {
        let value = null
        
        if (rowIndex !== null && rowData) {
          // 动态表格行数据
          value = rowData[param.paramCode]
        } else if (childGroupId) {
          // 嵌套子组数据
          value = this.getChildGroupData(groupId, childGroupId)[param.paramCode]
        } else {
          // 普通组数据
          value = this.getGroupData(groupId)[param.paramCode]
        }
        
        callback(param, value, { groupId, childGroupId, rowIndex })
      })
    },
    
    /**
     * 按类型统计参数
     */
    countParamsByType(paramType) {
      let count = 0
      this.traverseParams((param) => {
        if (param.paramType === paramType) count++
      })
      return count
    }
  }
}
</script>

<style scoped>
.test-data-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.data-navigation {
  margin-bottom: 20px;
}

.data-section {
  flex: 1;
  overflow-y: auto;
}

.param-group {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.group-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.nested-groups {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.child-group {
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.child-group-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
  font-weight: 600;
}

.dynamic-table-group {
  background: white;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.normal-group {
  background: white;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.data-stats {
  margin-top: 20px;
}

.stats-header {
  font-weight: 600;
}

.stats-content {
  padding: 10px 0;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .param-group {
    padding: 12px;
  }
  
  .stats-content .el-col {
    margin-bottom: 10px;
  }
}
</style>